package com.dgty.dg_common.widget.tv;

import android.content.Context;
import android.graphics.Color;
import android.text.Spannable;
import android.text.method.MovementMethod;
import android.util.AttributeSet;
import android.view.MotionEvent;

/**
 * Title: QMUISpanTouchFixTextView
 * Description:
 * Created DateTime: 2023-03-08 14:00
 * Created by xxl.
 */
public class QMUISpanTouchFixTextView extends androidx.appcompat.widget.AppCompatTextView {
    private boolean mTouchSpanHint;

    // 记录每次真正传入的press，每次更改mTouchSpanHint，需要再调用一次setPressed，确保press状态正确
    private boolean mIsPressedRecord = false;
    private boolean mShouldConsumeEvent = true; // TextView是否应该消耗事件

    public QMUISpanTouchFixTextView(Context context) {
        this(context, null);
    }

    public QMUISpanTouchFixTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public QMUISpanTouchFixTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setHighlightColor(Color.TRANSPARENT);
        setMovementMethod(QMUILinkTouchMovementMethod.getInstance());
    }

    public void setShouldConsumeEvent(boolean shouldConsumeEvent) {
        mShouldConsumeEvent = shouldConsumeEvent;
        setFocusable(shouldConsumeEvent);
        setClickable(shouldConsumeEvent);
        setLongClickable(shouldConsumeEvent);
    }

    public void setMovementMethodCompat(MovementMethod movement){
        setMovementMethod(movement);
        if(!mShouldConsumeEvent){
            setShouldConsumeEvent(false);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!(getText() instanceof Spannable)) {
            return super.onTouchEvent(event);
        }
        mTouchSpanHint = true;
        // 调用super.onTouchEvent,会走到QMUILinkTouchMovementMethod
        // 会走到QMUILinkTouchMovementMethod#onTouchEvent会修改mTouchSpanHint
        boolean ret = super.onTouchEvent(event);
        if(!mShouldConsumeEvent){
            return mTouchSpanHint;
        }
        return ret;
    }

    public void setTouchSpanHint(boolean touchSpanHint) {
        if (mTouchSpanHint != touchSpanHint) {
            mTouchSpanHint = touchSpanHint;
            setPressed(mIsPressedRecord);
        }
    }

    @Override
    public boolean performClick() {
        if (!mTouchSpanHint && mShouldConsumeEvent) {
            return super.performClick();
        }
        return false;
    }

    @Override
    public boolean performLongClick() {
        if (!mTouchSpanHint && mShouldConsumeEvent) {
            return super.performLongClick();
        }
        return false;
    }

    @Override
    public final void setPressed(boolean pressed) {
        mIsPressedRecord = pressed;
        if (!mTouchSpanHint) {
            onSetPressed(pressed);
        }
    }

    protected void onSetPressed(boolean pressed) {
        super.setPressed(pressed);
    }

}
